<template>
  <div>
    <template v-for="(tag, index) in tags">
      <a-tooltip v-if="tag.length > 10" :key="tag" :title="tag">
        <a-tag :key="tag" :closable="true" @close="() => handleClose(tag)">
          {{ `${tag.slice(0, 10)}...` }}
        </a-tag>
      </a-tooltip>
      <a-tag v-else :key="tag" :closable="true" @close="() => handleClose(tag)">
        {{ tag }}
      </a-tag>
    </template>
    <a-input
      v-if="inputVisible"
      ref="input"
      type="text"
      size="small"
      :style="{ width: '78px' }"
      :value="inputValue"
      @change="handleInputChange"
      @blur="handleInputConfirm"
      @keyup.enter="handleInputConfirm"
    />
    <a-tag v-else style="background: #fff; borderStyle: dashed;" @click="showInput">
      <a-icon type="plus" /> {{newText}}
    </a-tag>
  </div>
</template>

<script>
    export default {
      name: 'AkTags',
      props:{
        value:{
          required:false,
          type:Array,
          default:[],
        },
        newText:{
          required: false,
          type:String,
          default:'New Tag'
        }
      },
      watch:{
        value(val){
          this.tags = val;
        }
      },
      mounted(){
        this.tags = this.value;
      },
      data() {
        return {
          tags: ['Unremovable', 'Tag 2', 'Tag 3Tag 3Tag 3Tag 3Tag 3Tag 3Tag 3'],
          inputVisible: false,
          inputValue: '',
        };
      },
      methods: {
        handleClose(removedTag) {
          const tags = this.tags.filter(tag => tag !== removedTag);
          this.tags = tags;
          this.$emit('change', this.tags);
        },

        showInput() {
          this.inputVisible = true;
          this.$nextTick(function () {
            this.$refs.input.focus();
          });
        },

        handleInputChange(e) {
          this.inputValue = e.target.value;
        },

        handleInputConfirm() {
          const inputValue = this.inputValue;
          let tags = this.tags;
          if (inputValue && tags.indexOf(inputValue) === -1) {
            tags = [...tags, inputValue];
          }
          Object.assign(this, {
            tags,
            inputVisible: false,
            inputValue: '',
          });
          this.$emit('change', this.tags);
        },
      },
      model: {
        prop: 'value',
        event: 'change'
      }
    }
</script>

<style scoped>

</style>